package com.design.proxy;

import com.design.ICacheAdapter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * jdk动态代理需要实现invocationHandler接口
 * @author ytj
 * @date 2021/12/24
 */
public class JdkInvocationHandle implements InvocationHandler {
    private ICacheAdapter iCacheAdapter;

    public JdkInvocationHandle(ICacheAdapter iCacheAdapter){
        this.iCacheAdapter=iCacheAdapter;
    }

    /**
     * 动态代理执行方法
     * */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return ICacheAdapter.class.getMethod(method.getName(),getClazzByArgs(args)).invoke(iCacheAdapter,args);
    }

    /**
     * 类型转换
     * */
    public  Class<?>[] getClazzByArgs(Object[] args) {
        Class<?>[] parameterTypes = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof ArrayList) {
                parameterTypes[i] = List.class;
                continue;
            }
            if (args[i] instanceof LinkedList) {
                parameterTypes[i] = List.class;
                continue;
            }
            if (args[i] instanceof HashMap) {
                parameterTypes[i] = Map.class;
                continue;
            }
            if (args[i] instanceof Long){
                parameterTypes[i] = long.class;
                continue;
            }
            if (args[i] instanceof Double){
                parameterTypes[i] = double.class;
                continue;
            }
            if (args[i] instanceof TimeUnit){
                parameterTypes[i] = TimeUnit.class;
                continue;
            }
            parameterTypes[i] = args[i].getClass();
        }
        return parameterTypes;
    }
}
